<template>
  <div>
    <card-group-solt
            @handleClick="changeTab"
            :activeName="activeName"
            :tabPanes="tabPanes"
            :cardLoading="loading"
            loading="true">
      <template slot="search">
        <!--高级搜索-->
        <!--稍后处理-->
        <!-- <search type="webchat_laterProcess" v-if="loadedList.has('webchat_laterProcess')" v-show="activeName === 'webchat_laterProcess'"> -->
          <!--输入名称搜索-->
          <!-- <template :slot="'inputSearch'"> -->
            <!-- <input-search -->
              <!-- :placeHolder="$t('webchat.pleaseEnter')" -->
              <!-- @quickSearch="handlerQuickSearch" -->
              <!-- :form="search.webchat_laterProcess.isChildren.nomalForm"> -->
            <!-- </input-search> -->
          <!-- </template> -->
          <!-- <template :slot="'advancedSearch'"> -->
            <!--高级搜索组件-->
            <!-- <advanced-search
              v-if="activeName === 'webchat_laterProcess'"
              :adv="search.webchat_laterProcess.isChildren.adv"
              :formItemsConfig="formItemsConfigs.webchat_laterProcess"
              @advSearch="advSearch"
              @selectChange="handlerSelectChange"
              @confirmNewItemsConfig="handleConfirmNewItemsConfig($event, 'webchat_laterProcess')"
            >
            </advanced-search> -->
          <!-- </template>
          <template :slot="'refresh'">
            <refresh @refresh="handleRefresh" :class="'positionClass'"></refresh>
          </template>
          <template :slot="'advSchBadge'">
            <advSchBadge
              :badge="search.webchat_laterProcess.isChildren.adv.badgeList"
              @removeBadge="removeBadge">
            </advSchBadge>
          </template>
        </search> -->
        <!--全部-->
        <search type="webchat_all" v-if="loadedList.has('webchat_all')" v-show="activeName === 'webchat_all'">
          <template :slot="'select'">
            <v-select
              :selectOptions="search.webchat_all.isChildren.select"
              :form="search.webchat_all.isChildren.nomalForm"
              @quickSelect="handlerQuickSelect"></v-select>
          </template>
          <template :slot="'inputSearch'">
            <input-search
              :placeHolder="$t('webchat.pleaseEnter')"
              @quickSearch="handlerQuickSearch"
              :form="search.webchat_all.isChildren.nomalForm">
            </input-search>
          </template>
          <template :slot="'advancedSearch'">
            <advanced-search
              v-if="activeName === 'webchat_all'"
              :adv="search.webchat_all.isChildren.adv"
              :formItemsConfig="formItemsConfigs.webchat_all"
              :activeName="activeName"
              @advSearch="advSearch"
              @selectChange="handlerSelectChange"
              @confirmNewItemsConfig="handleConfirmNewItemsConfig($event, 'webchat_all')"
            >
            </advanced-search>
          </template>
          <template :slot="'refresh'">
            <refresh @refresh="handleRefresh" :class="'positionClass'"></refresh>
          </template>
          <template :slot="'advSchBadge'">
            <advSchBadge
              :badge="search.webchat_all.isChildren.adv.badgeList"
              @removeBadge="removeBadge">
            </advSchBadge>
          </template>
          <template :slot="'dropdownSelect'">
            <dropdown-menu :newEmptySeat="newEmptySeat" :tabType="'webchat'" @chatRecord="exportChatRecordDialog" @chatContent="exportChatContentDialog"></dropdown-menu>
          </template>
        </search>

        <!--机器人-->
        <search type="webchat_robot" v-if="loadedList.has('webchat_robot')" v-show="activeName === 'webchat_robot'">
          <template :slot="'inputSearch'">
            <input-search
              :placeHolder="$t('webchat.pleaseEnter')"
              @quickSearch="handlerQuickSearch"
              :form="search.webchat_robot.isChildren.nomalForm">
            </input-search>
          </template>
          <template :slot="'advancedSearch'">
            <advanced-search
              v-if="activeName === 'webchat_robot'"
              :adv="search.webchat_robot.isChildren.adv"
              :formItemsConfig="formItemsConfigs.webchat_robot"
              @advSearch="advSearch"
              @selectChange="handlerSelectChange"
              @confirmNewItemsConfig="handleConfirmNewItemsConfig($event, 'webchat_robot')"
            >
            </advanced-search>
          </template>
          <template :slot="'refresh'">
            <refresh @refresh="handleRefresh" :class="'positionClass'"></refresh>
          </template>
          <template :slot="'advSchBadge'">
            <advSchBadge
              :badge="search.webchat_robot.isChildren.adv.badgeList"
              @removeBadge="removeBadge">
            </advSchBadge>
          </template>
        </search>

        <!--处理中-->
        <search :type="'webchat_todo'" v-if="loadedList.has('webchat_todo')" v-show="activeName === 'webchat_todo'">
          <template :slot="'select'">
            <span class="font12">{{$t('webchat.sessionLimit')}}</span>
            <el-select size="mini" class="chat_limit" filterable v-model.trim="webchatLimit.value" placeholder="1" @change="handleChange">
              <el-option v-for="item in webchatLimit.options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
          <template :slot="'advancedSearch'">
            <time-search class="time_search" v-if="search.webchat_todo.isChildren.adv"
                         :isCommerce="true"
                         @timeSearch="timeSearch"
                         @inviteInfo="inviteInfo"
                         :webchatLimit="webchatLimit"
                         :resetSearch="resetTimeSearch"
            ></time-search>
          </template>
          <template :slot="'advSchBadge'">
            <advSchBadge v-if="search.webchat_todo.isChildren.adv.badgeList"
                         :badge="search.webchat_todo.isChildren.adv.badgeList" @removeBadge="removeBadge"></advSchBadge>
          </template>
        </search>

      </template>
      <template slot="pagination" v-if="this.$route.path.split('/')[2]==='webchat' && (activeName === 'webchat_all' || activeName === 'webchat_robot' || activeName === 'webchat_laterProcess')">
        <pagination
                :customerShow="true"
                :small="search[activeName].pagination.small"
                :currentPage="search[activeName].pagination.currentPage"
                :count="count"
                :moreFlag="moreFlag"
                :allCount="allCount"
                :type="type"
                :tabType="activeName"
                @turnPage="turnPage"
                :totalPage="totalPage"
                @getAllCount="getAllCount">
        </pagination>
      </template>
      <template slot="cardList">
        <!--<div class="loading" v-loading="loading" v-if="loading" :element-loading-text="$t('public.loadingDataText')"></div>-->
        <webchat-card
                :cardList="cardList"
                :count="count"
                :type="type"
                :qu="qu"
                :tabType="activeName"
                :searchStatus="searchStatus"
                v-show="!loading"
                :clearChecked="clearChecked"
                @refresh="handleRefresh"
                @changeCardItem="changeCardItem">
                <template v-slot:avatar="{item}">
                  <el-avatar class="avatar" :class="item.userStatus === 'online' && item.status !== 'finish' ? 'online': 'offline'" size="large" :src="item.headUrl" :icon="item.headUrl ? '' : 'el-icon-user-solid'"></el-avatar>
                </template>
        </webchat-card>
      </template>
    </card-group-solt>
    <pop-drag-conversation v-if="popConversationInfo.open" :conversationInfo="popConversationInfo" @close="closePopConversation"></pop-drag-conversation>
    <ExportDialog :isShow="exportDialogIsShow"
                  :exportHeads="exportHeads"
                  :isExportTask="isExportTask"
                  :exportType="exportDialogType"
                  :exportDialogTitle="exportDialogTitle"
                  :exportCustomerHeads="cusFieldArr"
                  @exportDialogCancelFun="exportDialogCancelFun"
                  @exportDialogDefineFun="exportDialogDefineFun"
                  v-if="exportDialogIsShow"
    ></ExportDialog>
  </div>
</template>
<script>
  import CardGroupSolt from '@/components/public-modules/card/NewIndex'
  import WebchatCard from '../webchat/WebchatCard'
  import PopDragConversation from '@/components/public-modules/popups/PopDragConversation'
  import Search from '@/components/public-modules/card/search/NewIndex.vue'
  import DropdownMenu from '@/components/public-modules/card/search/DropdownMenu.vue'
  import InputSearch from '@/components/public-modules/card/search/InputSearch'
  import AdvancedSearch from '@/components/public-modules/card/search/Advanced1Search'
  import AdvSchBadge from '@/components/public-modules/card/search/AdvSchBadge'
  import Pagination from '@/components/public-modules/card/Pagination'
  import {deepClone, getFormatDateTime, contains, updateAllOptions, initFinishName} from '@/utils/m7Utils'
  import TimeSearch from '../webchat/TimeSearch.vue'
  import Refresh from '../../ui-modules/icon/Refresh'
  import Export from '../../ui-modules/icon/Export'
  import Select from '@/components/public-modules/card/search/Select'
  import ExportDialog from '@/components/public-modules/export/exportDialog'
  import * as types from '@/store/modules/webchat/mutation-types.js'
  import * as gtypes from '@/store/mutation-types'
  import bus from '@/store/eventBus'
  import {LazyRender} from '@/mixins/LazyRender'
  export default {
    name: 'WebchatCardGroup',
    mixins: [LazyRender],
    watch: {
      refreshWebchatSummary: 'changeWebchatRight',
      $route (to, from) {
        const routeArr = to.path.split('/')
        if (routeArr[2] === 'webchat') {
          if (routeArr.length <= 4) {
            this.$store.commit('BLANK', routeArr[3])
          }
          if (to.query.flag === 'notify' && routeArr[3] === 'webchat_todo' && from.path.split('/')[2] === 'webchat') {
            this.changeTab('webchat_todo')
          }
          if (routeArr[4] === 'export') {
            this.changeTab('webchat_all', 'export')
          }
          if (this.$route.query && this.$route.query.status && this.$route.query.status === 'autoqcWebchat') {
            this.routeToMe(to, from)
          }
        } else {
          return
        }
      }
    },
    data () {
      return {
        chilidRouterData: {
          leaveUrl: '',
          onlineUrl: ''
        },
        childTab: [],
        // childTabActiveName: 'onlineSession',
        allCount: 0,
        qu: {},
        loading: true,
        activeName: this.$route.params.tabType || 'webchat_todo',
        PAGE_SIZE: 10,
        type: 'webchat',
        resetTimeSearch: false,
        clearChecked: 0,
        newEmptySeat: false,
        exportType: this.$store.state.isRealTimeExport ? 'real' : '', // real实时导出任务
        pages: 0,
        currentCardPage: 1,
        search: {
          isAdvSearch: false, // 是否在高级搜索
          isSearch: false,
          skillQueues: [], // 技能组
          webchatFinish: [], // 完成类型
          webchatSeoSource: [], // 搜索来源
          webchatCSR: [], // 满意类型
          searchQuery: {}, // 保存高级搜索条件用于导出
          webchat_todo: {
            searchCard: 'wtSearchCard',
            show: false,
            todoShow: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            isChildren: {
              lastQuery: null,
              rel: false,
              select: true,
              nomal: true,
              refresh: false,
              selfExport: false,
              adv: {
                form: {},
                advSearchOptions: {
                  localed: [],
                  custom: []
                },
                badgeList: {}
              }
            }
          },
          webchat_all: {
            searchCard: 'waSearchCard',
            show: true,
            todoShow: false,
            pagination: {
              small: true,
              currentPage: 1
            },
            isChildren: {
              lastQuery: null,
              rel: false,
              select: [
                { label: this.$t('webchat.lastWeek'), value: 'week' },
                { label: this.$t('webchat.today'), value: 'today' },
                { label: this.$t('webchat.yesterday'), value: 'yesterday' },
                { label: this.$t('webchat.lastMonth'), value: 'month' },
                { label: this.$t('public.all'), value: 'all' }
              ],
              nomal: true,
              refresh: true,
              selfExport: true,
              nomalForm: {query: '', flow: 'week', value: 'week'},
              adv: {
                form: {
                  sName: '',
                  ownercom: '',
                  user: '',
                  ownerdep: '',
                  status: '',
                  finishKey: '',
                  toPeer: '',
                  platform: '',
                  seoKeywords: '',
                  sessionType: [],
                  appraiseKey: '',
                  manualTime: [],
                  createTime: [],
                  beginTime: [],
                  endTime: [],
                  videoTime: [],
                  area: '',
                  seoSource: '',
                  mKeyword: '',
                  msgCountType: '',
                  msgCount: '',
                  robotStatusMsgCountType: '',    //  机器人消息条数查询类型  （大于||等于||小于）
                  robotStatusMsgCount: '',        //  机器人消息条数查询条数
                  showInvite: false,
                  accessList: [],       //  接入号查询
                  activeClaimType: [],
                  robotSession: '',
                  initiating: '',
                  fromUser: ''
                },
                advSearchOptions: {
                  localed: [],
                  custom: []
                },
                badgeList: {}
              }
            }
          },
          webchat_robot: {
            searchCard: 'waSearchCard',
            show: true,
            todoShow: false,
            pagination: {
              small: true,
              currentPage: 1
            },
            isChildren: {
              lastQuery: null,
              rel: false,
              nomal: true,
              refresh: true,
              selfExport: true,
              nomalForm: {query: '', flow: '', value: ''},
              adv: {
                form: {
                  sName: '',
                  toPeer: '',
                  createTime: [],
                  robotStatusMsgCountType: '',
                  robotStatusMsgCount: '',
                  accessList: [],  // 接入号查询
                  platform: ''     // 平台来源
                },
                advSearchOptions: {
                  localed: [],
                  custom: []
                },
                badgeList: {}
              }
            }
          },
          webchat_laterProcess: {
            searchCard: 'waSearchCard',
            show: true,
            todoShow: false,
            pagination: {
              small: true,
              currentPage: 1
            },
            isChildren: {
              lastQuery: null,
              rel: false,
              nomal: true,
              refresh: true,
              selfExport: true,
              nomalForm: {query: '', flow: '', value: ''},
              adv: {
                form: {
                  sName: '',  // 用户名
                  toPeer: '', // 技能组
                  mKeyword: '', // 会话内容
                  createTime: []  // 创建时间
                },
                advSearchOptions: {
                  localed: [],
                  custom: []
                },
                badgeList: {}
              }
            }
          }
        },
        popConversationInfo: {
          name: '',
          open: false,
          loading: true
        },
        searchStatus: '', // 当前搜索卡片的状态
        formItemsConfigs: {},
        exportTaskLimit: {},
        exportDialogIsShow: false,
        exportDialogTitle: this.$t('public.webchat'),
        isExportTask: false,
        exportDialogType: '',
        exportHeads: [
          {name: '_id', value: this.$t('webchat.exportHead.sessionID')},
          {name: 'sName', value: this.$t('webchat.sName')},
          {name: 'customerName', value: this.$t('public.customerName')},
          {name: 'customerPhone', value: this.$t('public.contactWay')},
          {name : 'agent', value: this.$t('webchat.exportHead.deelAgent')},
          {name : 'toPeer', value: this.$t('webchat.fromSkillGroup')},
          {name : 'ip', value: this.$t('webchat.exportHead.IP')},
          {name : 'area', value: this.$t('webchat.are')},
          {name: 'seoSource', value: this.$t('webchat.searchForSource')},
          {name: 'seoKeywords', value: this.$t('report.seoKeywords')},
          {name: 'lastSpeaker', value: this.$t('webchat.exportHead.lastSendMsgUser')},
          {name: 'createTime', value: this.$t('webchat.exportHead.sessionCreatTime')},
          {name: 'manualTime', value: this.$t('webchat.exportHead.sessionAccessTime')},
          {name: 'lastTimeStamp', value: this.$t('webchat.exportHead.sessionLastMsgTime')},
          {name: 'endTime', value: this.$t('webchat.exportHead.closeSessionTime')},
          {name: 'firstReplyTime', value: this.$t('webchat.exportHead.firstResponseTime')},
          {name: 'beginTime', value: this.$t('webchat.agentTakeTime')},
          {name: 'agentFirstReplyTime', value: this.$t('webchat.exportHead.agentFirstResTime')},
          {name: 'agentFirstReplyTimeLength', value: this.$t('webchat.exportHead.agentFirstResTimeLength')},
          {name: 'duration', value: this.$t('webchat.dialogueDuration')},
          {name: 'accessId', value: this.$t('webchat.imAccessId')},
          {name: 'platform', value: this.$t('webchat.platformSource')},
          {name: 'fromUrl', value: this.$t('webchat.exportHead.consultationPage')},
          {name: 'totalMsgCount', value: this.$t('webchat.exportHead.msgTotalNum')},
          {name: 'replyMsgCount', value: this.$t('webchat.exportHead.agentRelpyMsgNum')},
          {name: 'referrer', value: this.$t('webchat.searchForSourceUpper')},
          {name: 'landingPageUrl', value: this.$t('report.Leading')},
          {name: 'quality', value: this.$t('webchat.exportHead.sessionQuality')},
          {name: 'appraiseSatisFaction', value: this.$t('webchat.exportHead.evaluationInfo')},
          {name: 'appraiseLabel', value: this.$t('webchat.exportHead.evalutionLabel')},
          {name: 'appraiseProposal', value: this.$t('webchat.exportHead.evalutionDetails')},
          {name: 'finishReason1', value: this.$t('webchat.exportHead.closeSessionType', {Num: '1'})},
          {name: 'finishReason2', value: this.$t('webchat.exportHead.closeSessionType', {Num: '2'})},
          {name: 'finishReason3', value: this.$t('webchat.exportHead.closeSessionType', {Num: '3'})},
          {name: 'remark', value: this.$t('public.remark')}
        ],
        cusFieldArr: []
      }
    },
    provide () {
      return {
        itemsDisabled: {
          webchat_all: {
            createTime: true
          }
        }
      }
    },
    beforeMount () {
      this.allCount = 0
      let data = {
        page: 1,
        limit: 10
      }
      let that = this
      this.search[this.activeName].isChildren.lastQuery = data
      this.getWebchatList(this.$store, this.activeName, data).then(() => {
        if (data.page === 1) {
          this.pages = this.count / this.PAGE_SIZE
        }
        that.loading = false
        that.$store.commit(types.CHANGE_LOAD_STATUS, {})
      })

      // 高级搜索
      Promise.all([
        this.$store.dispatch('getCache', { type: 'mailQueues' }),
        this.$store.dispatch('getCache', { type: 'channelDic' }),
        this.$store.dispatch('getAdvSearchConfig', {searchType: 'WebchatCardGroup'}), // 高级搜索布局配置
        this.$store.dispatch('getCache', { type: 'webchatAndSdkConfig' }) // 获取在线咨询接入号列表
      ]).then(([mailQueues, channelDic, config, accessList]) => {
        let skillQueues = [...mailQueues.map(item => ({ label: item.DisplayName, value: `${item.Exten}__${item.DisplayName}` }))]
        let accessArray = [...accessList.map(item => ({ label: item.name, value: `${item.accessId}__${item.name}` }))]
        // 机器人会话 筛选
        let robotskillQueues = []
        let currentUserId = this.$store.state.session.user._id
        if (this.$store.state.session.user.funcIds && contains(this.$store.state.session.user.funcIds, 'func_robot_session') && this.$store.state.session.user.type !== 'manager') {
          mailQueues.forEach((item) => {
            let obj = deepClone(item)
            let dataLi = {
              AssignMembers: []
            }
            let grrowName = obj._id
            let grrowIdexOf = grrowName.indexOf(currentUserId)
            if (obj.AssignMembers.length) {
              for (let i = 0; i < obj.AssignMembers.length; i++) {
                let liName = obj.AssignMembers[i].agentID
                if (liName.indexOf(currentUserId) !== -1) {
                  dataLi.AssignMembers.push(obj.AssignMembers[i])
                }
              }
              if (dataLi.AssignMembers.length) {
                obj.AssignMembers = dataLi.AssignMembers
                robotskillQueues.push({ label: obj.DisplayName, value: `${obj.Exten}__${obj.DisplayName}` })
              } else if (grrowIdexOf !== -1) {
                robotskillQueues.push({ label: obj.DisplayName, value: `${obj.Exten}__${obj.DisplayName}` })
              }
            }
          })
        } else {
          robotskillQueues = deepClone(skillQueues)
        }

        let seoSources = this.getChannelDicByType('webchatSeoSource')
        let webchatSeoSource = [{ label: this.$t('public.all'), value: '' }, ...seoSources.map(item => ({ label: item.name, value: `${item.name}__${item.name}` }))]

        let finishTypes = this.getChannelDicByType('webchat')
        let webchatFinish = [
          {name: this.$t('public.all'), key: '' }, ...finishTypes,
          {name: this.$t('webchat.addBlack'), key: `add_black__${this.$t('webchat.addBlack')}`},
          {name: this.$t('webchat.queueGiveUp'), key: `queueGiveUp__${this.$t('webchat.queueGiveUp')}`},
          {name: this.$t('webchat.noScheduleMatch'), key: `noScheduleMatch__${this.$t('webchat.noScheduleMatch')}`},
          {name: this.$t('webchat.processFinish'), key: `finishByProcess__${this.$t('webchat.processFinish')}`},
          {name: this.$t('webchat.formQuit'), key: `formQuit__${this.$t('webchat.formQuit')}`},
          {name: this.$t('webchat.notConnectedToTheSession'), key: `noAccess__${this.$t('webchat.notConnectedToTheSession')}`},
        ]
        let webchatFinishArr = []
        updateAllOptions(webchatFinish, {Arr: webchatFinishArr})
        let CSRShowToAgent = getCache('CSRShowToAgent') || 'all'
        console.log(CSRShowToAgent)
        this.finishOptions = initFinishName(webchatFinish, {})
        let webchatCSRS = this.getChannelDicByType('webchatCSR')
        let webchatCSR = [{ label: this.$t('public.all'), value: '' }, ...webchatCSRS.map(item => ({ label: item.name, value: `${item.key}__${item.name}` }))]
        let localedOptionsOne = [
          {label: this.$t('webchat.userName'), name: 'sName', inputType: 'input'},
          {label: this.$t('webchat.master'), name: 'ownercom', inputType: 'owner'},
          {
            label: this.$t('public.state'),
            name: 'status',
            inputType: 'select',
            data: [
              {label: this.$t('webchat.webchatAll'), value: ''},
              {label: this.$t('webchat.undeal'), value: `undeal__${this.$t('webchat.undeal')}`},
              {label: this.$t('webchat.received'), value: `deal__${this.$t('webchat.received')}`},
              {label: this.$t('webchat.closed'), value: `finish__${this.$t('webchat.closed')}`},
              {label: this.$t('webchat.transfer'), value: `changePeer__${this.$t('webchat.transfer')}`}
            ]
          },
          {label: this.$t('webchat.processResult'), filterable: true, name: 'finishKey', inputType: 'webchatFinish', data: webchatFinishArr},
          {label: this.$t('public.queues'), filterable: true, name: 'toPeer', inputType: 'select', data: skillQueues, multiple: true},
          {label: this.$t('webchat.imAccessId'), filterable: true, name: 'accessList', inputType: 'select', data: accessArray, multiple: true},
        ]
        let localedOptionsTwo = [
          {
            label: this.$t('webchat.platformSource'),
            name: 'platform',
            inputType: 'select',
            data: [
              {label: this.$t('webchat.webchatAll'), value: ''},
              {label: this.$t('webchat.websiteCon'), value: `pc__${this.$t('webchat.websiteCon')}`},
              {label: this.$t('webchat.wapCon'), value: `wap__${this.$t('webchat.wapCon')}`},
              {label: this.$t('webchat.appCon'), value: `sdk__${this.$t('webchat.appCon')}`},
              {label: this.$t('webchat.weChatCon'), value: `weixin__${this.$t('webchat.weChatCon')}`},
              {label: this.$t('webchat.weChatMini'), value: `wxmini__${this.$t('webchat.weChatMini')}`},
              // {label: this.$t('webchat.weBoCon'), value: `weibo__${this.$t('webchat.weBoCon')}`}
            ]
          },
          {label: this.$t('webchat.are'), name: 'area', inputType: 'input'},
          {label: this.$t('webchat.searchForSource'), name: 'seoSource', inputType: 'select', data: webchatSeoSource},
          {label: this.$t('webchat.seoKeywords'), name: 'seoKeywords', inputType: 'input'},
          {
            label: this.$t('webchat.sessionType'),
            name: 'sessionType',
            inputType: 'select',
            data: [
              {label: this.$t('webchat.webchatAll'), value: ''},
              {label: this.$t('webchat.onlineSession'), value: `chat__${this.$t('webchat.onlineSession')}`},
              {label: this.$t('webchat.leaveMessage'), value: `leave__${this.$t('webchat.leaveMessage')}`}
            ]
          },
          {label: this.$t('webchat.laborTime'), name: 'manualTime', inputType: 'time', data: []},
          {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time', data: []},
          {label: this.$t('webchat.sessionContent'), name: 'mKeyword', inputType: 'input', placehoder: this.$t('webchat.sessionContentPlaceholder')},
          {label: this.$t('webchat.takeTime'), name: 'beginTime', inputType: 'time', data: []},
          {label: this.$t('public.endTime'), name: 'endTime', inputType: 'time', data: []},
          {label: this.$t('webchat.isClaim'), name: 'activeClaimType', inputType: 'select', data: [{label: this.$t('webchat.robotChat'), value: 'robot'}], multiple: true},
          {label: this.$t('webchat.activeSession'), name: 'showInvite', inputType: 'checkbox', data: [{label: this.$t('public.yes'), value: `showInvite__${this.$t('webchat.activeSession')}`}]},
          {label: this.$t('webchat.TransferChat'), name: 'fromUser', inputType: 'checkbox', data: [{label: this.$t('public.yes'), value: `fromUser__${this.$t('webchat.TransferChat')}`}]},
          {label: this.$t('public.videoEndTime'), name: 'videoTime', inputType: 'time', data: []},
          {label: this.$t('webchat.initiatingSession'), name: 'initiating', inputType: 'checkbox', data: [{label: this.$t('public.yes'), value: `initiating__${this.$t('webchat.initiatingSession')}`}]},
          {label: this.$t('webchat.msgNum'), inputType: 'radioInput', name: 'msgCount', radioName: 'msgCountType', inputName: 'msgCount', data: []},
          {label: this.$t('webchat.robotMsgNum'), inputType: 'radioInput', name: 'robotStatusMsgCount', radioName: 'robotStatusMsgCountType', inputName: 'robotStatusMsgCount', data: []},   //  机器人消息条数查询  robotStatusMsgCountTypeA:小于||等于||大于  robotStatusMsgCount:条数
          {label: this.$t('webchat.robotSession'), name: 'robotSession', inputType: 'checkbox', data: [{label: this.$t('public.yes'), value: `robot__${this.$t('webchat.robotSession')}`}]}
        ]
  
        let localedRobotOptions = [
          {label: this.$t('webchat.userName'), name: 'sName', inputType: 'input'},
          {label: this.$t('public.queues'), filterable: true, name: 'toPeer', inputType: 'select', data: robotskillQueues, multiple: true},
          {label: this.$t('webchat.imAccessId'), filterable: true, name: 'accessList', inputType: 'select', data: accessArray, multiple: true},
          {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time', data: []},
          {label: this.$t('webchat.msgNum'), name: 'msgNum', inputType: 'radioInput', radioName: 'robotStatusMsgCountType', inputName: 'robotStatusMsgCount', data: []},
          {
            label: this.$t('webchat.platformSource'),
            name: 'platform',
            inputType: 'select',
            data: [
              {label: this.$t('webchat.webchatAll'), value: ''},
              {label: this.$t('webchat.websiteCon'), value: `pc__${this.$t('webchat.websiteCon')}`},
              {label: this.$t('webchat.wapCon'), value: `wap__${this.$t('webchat.wapCon')}`},
              {label: this.$t('webchat.appCon'), value: `sdk__${this.$t('webchat.appCon')}`},
              {label: this.$t('webchat.weChatCon'), value: `weixin__${this.$t('webchat.weChatCon')}`},
              {label: this.$t('webchat.weChatMini'), value: `wxmini__${this.$t('webchat.weChatMini')}`}
              // {label: this.$t('webchat.weBoCon'), value: `weibo__${this.$t('webchat.weBoCon')}`}
            ]
          }
        ]
        let localedLaterProcessOptions = [
          {label: this.$t('webchat.userName'), name: 'sName', inputType: 'input'},
          {label: this.$t('public.queues'), filterable: true, name: 'toPeer', inputType: 'select', data: skillQueues, multiple: true},
          {label: this.$t('webchat.imAccessId'), filterable: true, name: 'accessList', inputType: 'select', data: accessArray, multiple: true},
          {label: this.$t('webchat.sessionContent'), name: 'mKeyword', inputType: 'input'},
          {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time', data: []}
        ]
        let newLocaledOptions = []
        if (CSRShowToAgent === 'all') {
          newLocaledOptions = [
            ...localedOptionsOne,
            {
              label: this.$t('webchat.satisfactioEvaluation'),
              name: 'appraiseKey',
              inputType: 'select',
              data: webchatCSR
            },
            ...localedOptionsTwo,
          ]
        } else {
          newLocaledOptions = [
            ...localedOptionsOne,
            ...localedOptionsTwo,
          ]
        }
        console.log(newLocaledOptions)
        this.search.webchat_all.isChildren.adv.advSearchOptions.localed = deepClone(newLocaledOptions)
        this.search.webchat_robot.isChildren.adv.advSearchOptions.localed = deepClone(localedRobotOptions)
        this.search.webchat_laterProcess.isChildren.adv.advSearchOptions.localed = deepClone(localedLaterProcessOptions)
        if (this.$route.query && this.$route.query.status && this.$route.query.status === 'autoqcWebchat') {
          this.routeToMe(this.$route.path)
        }
        this.formItemsConfigs = config || {}
      })
      // 导出关联客户字段
      this.$store.dispatch('getCache', {type: 'custTmpls'}).then((res) => {
        if (res.length <= 0) { // 新开的账户，没有数据
          return
        }
        let _stable_fields = res[0].stable_fields || []
        for (let i = 0; i < _stable_fields.length; i++) {
          if (!_stable_fields[i].isShow) {
            this.cusFieldArr.push({
              name: _stable_fields[i].name,
              value: _stable_fields[i].value
            })
          }
        }
        let _arr = [
          {name: 'owner', value: this.$t('customer.ownerPeople')},
          {name: 'ownerNo', value: this.$t('webchat.exportHead.agentNum')},
          {name: 'status', value: this.$t('webchat.exportHead.custStatus')},
          {name: 'source', value: this.$t('customer.dataSource')},
          {name: 'creator', value: this.$t('public.creator')},
          {name: 'createTime', value: this.$t('webchat.createTime')},
          {name: 'lastUpdateTime', value: this.$t('monitor.updateTime')},
          {name: 'attachs', value: this.$t('public.attach')},
          {name: 'customFields', value: this.$t('customer.customField')},
          {name: 'sysStatus', value: this.$t('customer.sysStatus')},
          {name: 'categoryId', value: this.$t('customer.categoryId')}
        ]
        this.cusFieldArr = [...this.cusFieldArr, ..._arr]
      })
      // this.initLimitNum()
    },
    methods: {
      // 查询当前tab下的list
      getWebchatList (store, tabName, data, isClaim) {
        this.qu = deepClone(data)
        if (isClaim && isClaim === 'isClaim') {
          data.page = this.currentCardPage
          data.morePage = 1
          if (this.currentCardPage >= this.pages && this.currentCardPage % this.pages === 0) {
            data.morePage = this.currentCardPage / this.pages + 1
          } else {
            data.morePage = Math.floor(this.currentCardPage / this.pages + 1)
          }
        } else {
          if (!data.morePage) {
            data.morePage = 1
          }
        }
        if (tabName === 'webchat_laterProcess') {
          // 稍后处理参数
          data.laterProcess = true
        }
        data.submenu = tabName
        if (tabName === 'webchat_robot') { // 机器人会话列表
          data.status = 'robot'
          return store.dispatch('queryWebchatSessionByStatus', data)
        } else {
          return store.dispatch('queryWebchatList', data)
        }
      },
      getAllCount () {
        this.allCount = 0
        let form = this.qu
        form.queryCount = true
        form.searchAllCount = true // 此参数是防止vuex的值被改动
        let activeName = this.activeName
        let more = false
        this.getWebchatList(this.$store, this.activeName, form).then((resp) => {
          delete this.qu.searchAllCount
          if (resp && resp.success) {
            this.allCount = resp.count
            this.$store.commit('webchat/SET_WEBCHAT_MORE', {activeName, more})
            this.loading = false
          }
        })
      },
      setQuickSeachTitle (value) {
        if (this.search[this.activeName].isChildren.nomalForm) {
          this.search[this.activeName].isChildren.nomalForm.flow = value
          this.search[this.activeName].isChildren.nomalForm.value = value
        }
      },
      /*
      * 查询的时候数据
      * */
      searchDataReturn (value) {
        let nowTime = new Date()
        let mtDate = nowTime.getTime()
        let startTime = ''
        let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
        if (value === 'week') {
          // 近一周
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 7)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'today') {
          // 今天
          startTime = getFormatDateTime(new Date(mtDate)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'yesterday') {
          // 昨天
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 00:00:00'
          endTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 23:59:59'
        } else if (value === 'month') {
          // 近一月
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 30)).split(' ')[0] + ' 00:00:00'
        } else {
          endTime = ''
        }
        if (value) {
          let end = new Date()
          let start = new Date()
          if (value === 'week') {
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          //  } else if (value === 'today') {
          //    start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
          } else if (value === 'yesterday') {
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
          } else if (value === 'month') {
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          }
          let arr = [new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0), new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)]
          if (value === 'all') {
            arr = []
          }
          this.$set(this.search.webchat_all.isChildren.adv.form, 'createTime', arr)
        }

        if (this.activeName === 'webchat_all') {
          let searchQuery = {
            createTimeBegin: startTime,
            createTimeEnd: endTime,
            limit: 10,
            page: 1
          }
          return searchQuery
        } else {
          return {
            limit: 10,
            page: 1
          }
        }
      },
      /**
       * 快捷搜索一周 一月 一年
       */
      handlerQuickSelect (value) {
        this.allCount = 0
        this.searchStatus = ''  // 当前的高级搜索中的状态
        this.search.isSearch = true
        this.search.isAdvSearch = false
        this.clearSearchQuery()
        this.setQuickSeachTitle(value)
        let searchQuery = this.searchDataReturn(value)
        this.loading = true
        if (this.search[this.activeName]) {
          this.search[this.activeName].pagination.currentPage = 1
          this.search[this.activeName].isChildren.lastQuery = searchQuery
        }
        this.getWebchatList(this.$store, this.activeName, searchQuery).then(() => {
          this.pages = this.count / this.PAGE_SIZE
          this.loading = false
        })
      },
      queryWebchatListCount (store, tabName, data) {
        data.submenu = tabName
        data.queryCount = true
        return store.dispatch('queryWebchatListCount', data)
      },
      changeCardItem () {
        this.$emit('changeCardItem')
      },
      changeWebchatRight () {
        let path = this.$route.path.split('/')
        if (path.length > 3 && path[3] === 'webchat_todo' && path[4] === this.refreshWebchatSummary) {
          this.$store.commit('BLANK', 'webchat_todo')
          this.$router.replace({path: '/index/webchat/webchat_todo'})
        }
      },
      timeSearch (data) {
        this.resetTimeSearch = false
        this.loading = true
        let searchQuery = deepClone(data)
        let tempObj = this.advSearchBack(searchQuery)
        if (data.visitorsReply || data.unReply || data.clientReply) {
          this.$store.dispatch('updateTimeSearchState', true).then(() => {
            this.$store.commit('BLANK', 'webchat_todo')
            this.$router.push({path: '/index/webchat/webchat_todo'})
          })
        }
        this.search[this.activeName].isChildren.adv.badgeList = tempObj
        this.search[this.activeName].isChildren.lastQuery = searchQuery
        this.getWebchatList(this.$store, this.activeName, searchQuery).then(() => {
          this.pages = this.count / this.PAGE_SIZE
          this.loading = false
        })
      },
      pushWebchatTodoRoute (url) {
        this.$router.push({path: url})
      },
      // 切换tab
      changeTab (tabName, type) {
        // 重置状态
        this.allCount = 0
        this.currentCardPage = 1  // 当前卡片的页数
        this.search.isSearch = true
        this.search.isAdvSearch = false
        if (this.search[this.activeName]) {
          this.search[this.activeName].pagination.currentPage = 1
        }
        if (this.activeName !== tabName) {
          this.clearSearchQuery()
        }
        this.activeName = tabName
        this.addLoad(this.activeName)
        if (type !== 'grabWebchatSession') {
          this.$store.commit('BLANK', tabName)
        }
        this.$emit('tabChange', tabName)
        if (tabName && tabName !== 'webchat_todo' && type !== 'export') {
          this.$router.push({path: '/index/webchat/' + tabName})
        }
        if (tabName === 'webchat_todo') {
          // this.removeBadge()
          //  高级搜索下抢接会话时   抢接会话直接跳转路由，导致高级搜索的条件没有删掉
          // 如果初始化过,就不必再初始化了
          if (this.$store.state.webchat.webchatList.webchat_todo.init) {
            return
          }
        }
        this.loading = true
        let data = {
          page: 1,
          limit: 10
        }
        // 重置全部下高级搜索默认时间
        if (tabName === 'webchat_all') {
          let end = new Date()
          let start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          let arr = [new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0), new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)]
          this.$set(this.search.webchat_all.isChildren.adv.form, 'createTime', arr)
          this.setQuickSeachTitle('week')
          data = Object.assign(data, this.searchDataReturn(this.search[this.activeName].isChildren.nomalForm.value))
          this.search[this.activeName].isChildren.lastQuery = data
        }
        this.getWebchatList(this.$store, this.activeName, data).then(() => {
          this.pages = this.count / this.PAGE_SIZE
          this.loading = false
        })
      },
      handleChange (option) {
        let that = this
        this.$store.dispatch('updateCurrentUser', {'imDealCount': option.toString()}).then(() => {
          that.$store.commit(gtypes.SET_SUCCESS, 'message.editSucess')
        })
      },
      turnPage (pageNum) {
        this.allCount = 0
        if (this.search.isSearch && pageNum < 2) {
          this.search.isSearch = false
          return
        }
        this.currentCardPage = pageNum
        this.search.isSearch = false
        this.loading = true
        let morePage = 1
        if (pageNum >= this.pages && pageNum % this.pages === 0) {
          morePage = pageNum / this.pages + 1
        } else {
          morePage = Math.floor(pageNum / this.pages + 1)
        }
        if (this.search[this.activeName]) {
          this.search[this.activeName].pagination.currentPage = pageNum
        }
        let queryData = Object.assign({}, this.search[this.activeName].isChildren.lastQuery, { page: pageNum, morePage })
        // let queryData = Object.assign({}, this.search[this.activeName].isChildren.lastQuery, { page: pageNum })
        this.getWebchatList(this.$store, this.activeName, queryData).then(() => {
          if (queryData.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          this.loading = false
        })
      },
      handlerQuickSearch (sName, isClaim) {
        this.allCount = 0
        this.search[this.activeName].isChildren.adv.badgeList = {} // 清除高级搜索项
        this.search.isSearch = true
        this.search.isAdvSearch = false
        this.loading = true
        this.search[this.activeName].isChildren.nomalForm.query = sName
        let query = {
          page: isClaim && isClaim === 'isClaim' ? this.currentCardPage : 1,
          limit: 10,
          sName: sName
        }
        if (this.search[this.activeName]) {
          this.search[this.activeName].pagination.currentPage = isClaim && isClaim === 'isClaim' ? this.currentCardPage : 1
        }
        let dataNew = Object.assign(query, this.searchDataReturn(this.search[this.activeName].isChildren.nomalForm.value))
        this.search[this.activeName].isChildren.lastQuery = query
        this.getWebchatList(this.$store, this.activeName, dataNew, isClaim).then((res) => {
          if (query.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          this.loading = false
          if (res && res.success) {
            if (this.currentCardPage > 1 && !res.list.length && this.activeName === 'webchat_robot' && isClaim && isClaim === 'isClaim') {
              this.handleRefresh()
            }
          }
        })
      },
      advSearch (reset, isClaim) {
        window._hmt && window._hmt.push(['_trackEvent', '其他统计', this.activeName + ' 高级搜索'])
        this.allCount = 0
        this.search.isSearch = true
        this.search.isAdvSearch = true
        if (reset) {
          this.clearSearchQuery()
        }
        let form = this.search[this.activeName].isChildren.adv.form
        let searchQuery = deepClone(form)
        let manualTime = form.manualTime
        let createTime = form.createTime
        let beginTime = form.beginTime
        let endTime = form.endTime
        let videoTime = form.videoTime

        // 消息数验证
        if (searchQuery.msgCountType || searchQuery.msgCount) {
          if (!searchQuery.msgCountType || !searchQuery.msgCount) {
            this.$message.error(this.$t('webchat.messagesNumNotEmpty'))
            return
          }
        }

        // 消息数验证
        if (searchQuery.robotStatusMsgCountType || searchQuery.robotStatusMsgCount) {
          if (!searchQuery.robotStatusMsgCountType || !searchQuery.robotStatusMsgCount) {
            this.$message.error(this.$t('webchat.messagesNumNotEmpty'))
            return
          }
        }

        // 人工时间
        if (manualTime) {
          if (manualTime[0]) {
            searchQuery.manualTimeBegin = getFormatDateTime(manualTime[0])
          }
          if (manualTime[1]) {
            searchQuery.manualTimeEnd = getFormatDateTime(manualTime[1])
          }
          delete searchQuery.manualTime
        }
        // 创建时间
        if (createTime) {
          if (createTime[0]) {
            searchQuery.createTimeBegin = getFormatDateTime(createTime[0])
          }
          if (createTime[1]) {
            searchQuery.createTimeEnd = getFormatDateTime(createTime[1])
          }
          delete searchQuery.createTime
          this.setQuickSeachTitle('all')
        }

        // 开始时间
        if (beginTime) {
          if (beginTime[0]) {
            searchQuery.beginTimeBegin = getFormatDateTime(beginTime[0])
          }
          if (beginTime[1]) {
            searchQuery.beginTimeEnd = getFormatDateTime(beginTime[1])
          }
          delete searchQuery.beginTime
        }

        // 结束时间
        if (endTime) {
          if (endTime[0]) {
            searchQuery.endTimeBegin = getFormatDateTime(endTime[0])
          }
          if (endTime[1]) {
            searchQuery.endTimeEnd = getFormatDateTime(endTime[1])
          }
          delete searchQuery.endTime
        }
        // 视频聊天发起时间
        if (videoTime) {
          if (videoTime[0]) {
            searchQuery.videoEndTimeBegin = getFormatDateTime(videoTime[0])
          }
          if (videoTime[1]) {
            searchQuery.videoEndTimeEnd = getFormatDateTime(videoTime[1])
          }
          delete searchQuery.videoTime
        }
        // 高级查询回显
        let tempObj = this.advSearchBack(searchQuery)
        if (this.search[this.activeName]) {
          this.search[this.activeName].isChildren.adv.badgeList = tempObj
        }

        // 结束类型
        if (searchQuery.finishKey) {
          searchQuery.finishKey = {'$in': this.getSubFinishKey(searchQuery.finishKey)}
        }
        let formFlag = false
        for (let x in searchQuery) {
          if (searchQuery[x]) {
            formFlag = true
          }
        }
        Object.assign(searchQuery, {
          page: 1,
          limit: 10
        })
        if (reset || !formFlag) {
          // this.search[this.activeName].isChildren.nomalForm.flow
          Object.assign(searchQuery, this.searchDataReturn('week'))
          this.setQuickSeachTitle('week')
          let end = new Date()
          let start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          let arr = [new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0), new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)]
          this.$set(this.search.webchat_all.isChildren.adv.form, 'createTime', arr)
        } else {
          this.setQuickSeachTitle('all')
        }
        this.loading = true
        if (this.search[this.activeName]) {
          this.search[this.activeName].pagination.currentPage = isClaim && isClaim === 'isClaim' ? this.currentCardPage : 1
          this.search[this.activeName].isChildren.lastQuery = searchQuery
        }
        this.searchStatus = searchQuery.status || ''
        if (isClaim && isClaim === 'isClaim') {
          searchQuery.page = this.currentCardPage
        }
        this.getWebchatList(this.$store, this.activeName, searchQuery, isClaim).then((res) => {
          if (searchQuery.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          this.loading = false
          if (res && res.success) {
            if (this.currentCardPage > 1 && !res.list.length && this.activeName === 'webchat_robot' && isClaim && isClaim === 'isClaim') {
              this.handleRefresh()
            }
          }
        })
      },
      advSearchBack (searchQuery) {
        let tmpObj = {}
        let that = this
        for (let key in searchQuery) {
          if (key === 'finishKey') {
            if (searchQuery[key] && searchQuery[key].length > 0) {
              searchQuery[key] = searchQuery[key][searchQuery[key].length - 1]
            } else {
              searchQuery[key] = ''
            }
          }
          if (searchQuery[key] && typeof searchQuery[key] === 'string') {
            if (searchQuery[key].match(/__/)) {
              tmpObj[key] = searchQuery[key].substr(searchQuery[key].indexOf('__') + 2)
              searchQuery[key] = searchQuery[key].substr(0, searchQuery[key].indexOf('__'))
            } else {
              tmpObj[key] = searchQuery[key]
            }
          }
          if (searchQuery[key] && Array.isArray(searchQuery[key]) && searchQuery[key].length > 0 && key !== 'activeClaimType' && key !== 'toPeer' && key !== 'accessList') {
            let tmpArr = []
            let tmpArr2 = []
            for (let i = 0; i < searchQuery[key].length; i++) {
              tmpArr.push(searchQuery[key][i].substr(searchQuery[key].indexOf('__') + 2))
              tmpArr2.push(searchQuery[key][i].substr(0, searchQuery[key].indexOf('__')))
            }
            tmpObj[key] = tmpArr
            searchQuery[key] = tmpArr2
          }
          if (searchQuery[key] && key === 'sessionType') { // 会话类型
            if (searchQuery[key] === '') {
              tmpObj[key] = that.$t('webchat.webchatAll')
            } else if (searchQuery[key] === 'chat') {
              tmpObj[key] = that.$t('webchat.onlineSession')
            } else if (searchQuery[key] === 'leave') {
              tmpObj[key] = that.$t('webchat.leaveMessage')
            }
          }
          if (searchQuery[key] && key === 'showInvite') { // 会话邀请
            tmpObj[key] = that.$t('webchat.activeSession')
          }
          if (searchQuery[key] && key === 'fromUser') {
            tmpObj[key] = that.$t('webchat.TransferChat')
          }
          if (searchQuery[key] && key === 'finishKey') {
            tmpObj[key] = that.finishOptions[searchQuery[key]] || tmpObj[key].substr(tmpObj[key].indexOf('__') + 2)
          }
          if (searchQuery[key] && key === 'activeClaimType') {
            if (searchQuery[key].length) {
              console.log(searchQuery[key].length)
              tmpObj[key] = this.$t('webchat.robotChat')
            }
          }
          if (searchQuery[key] && key === 'toPeer' && searchQuery[key].length) {
            tmpObj[key] = ''
            if (searchQuery[key].length) {
              for (let j = 0; j < searchQuery[key].length; j++) {
                let item = deepClone(searchQuery[key][j])
                let arr = item.split('__')
                searchQuery[key][j] = arr[0] || ''
                tmpObj[key] += ' ' + arr[1] || ''
              }
            }
          }
          if (searchQuery[key] && key === 'accessList' && searchQuery[key].length) {
            tmpObj[key] = ''
            if (searchQuery[key].length) {
              for (let j = 0; j < searchQuery[key].length; j++) {
                let item = deepClone(searchQuery[key][j])
                let arr = item.split('__')
                searchQuery[key][j] = arr[0] || ''
                tmpObj[key] += ' ' + arr[1] || ''
              }
            }
          }
          if (searchQuery[key] && key === 'initiating') { // 主动会话
            tmpObj[key] = that.$t('webchat.initiatingSession')
          }
          if (searchQuery[key] && key === 'robotSession') { // 仅机器人会话
            tmpObj[key] = that.$t('webchat.robotSession')
          }
        }
        return tmpObj
      },
      clearSearchQuery () {
        if (!(this.activeName === 'webchat_all' || this.activeName === 'webchat_todo' || this.activeName === 'webchat_robot' || this.activeName === 'webchat_laterProcess')) {
          return
        }
        let currentTab = this.search[this.activeName]
        if (currentTab) {
          currentTab.pagination.currentPage = 1
        }
        for (let key in currentTab.isChildren.adv.form) {
          if (Array.isArray(currentTab.isChildren.adv.form[key])) {
            currentTab.isChildren.adv.form[key] = []
          } else {
            if (key === 'robotSession' || key === 'initiating' || key === 'fromUser' || key === 'showInvite') {
              currentTab.isChildren.adv.form[key] = ''
            } else {
              currentTab.isChildren.adv.form[key] = null
            }
          }
        }
        for (let key in this.search[this.activeName].isChildren.nomalForm) {
          this.search[this.activeName].isChildren.nomalForm[key] = null
        }
        // this.search[this.activeName].isChildren.adv.badgeList = null
        for (let key in this.search[this.activeName].isChildren.nomalForm) {
          this.search[this.activeName].isChildren.nomalForm[key] = null
        }
        this.search[this.activeName].isChildren.lastQuery = null
      },
      handleRefresh (isClaim) {
        if (this.search.isAdvSearch) {
          this.advSearch('', isClaim)
        } else {
          this.handlerQuickSearch(this.search[this.activeName].isChildren.nomalForm.query, isClaim)
        }
      },
      handlerSelectChange (selectObj) {
        let selectName = selectObj.selectName
        let selectValue = selectObj.selectValue

        if (selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') {
          this.search[this.activeName].isChildren.adv.form.ownercom = null
          this.search[this.activeName].isChildren.adv.form.owner = null
          this.search[this.activeName].isChildren.adv.form.user = null
          this.search[this.activeName].isChildren.adv.form.ownerdep = null
          if (selectObj.selectName === 'owner') {
            this.search[this.activeName].isChildren.adv.form.user = selectValue
          } else {
            this.search[this.activeName].isChildren.adv.form[selectName] = selectValue
          }
        }
      },
      removeBadge () {
        this.advSearch(true)
        this.search.isAdvSearch = false
        this.resetTimeSearch = true
        this.clearChecked = Math.random()
        let that = this
        this.$store.dispatch('updateTimeSearchState', false).then(() => {
          if (that.$route.fullPath.split('/')[3] === 'webchat_todo') {
            this.$store.commit('BLANK', 'webchat_todo')
            that.$router.push({path: '/index/webchat/webchat_todo'})
          }
        })
      },
      // 获取options下所有key
      getSubFinishKey (superKey) {
        let result = [superKey]
        let finishMap = this.getSubFinishMap(superKey)
        let iteratorDic = function (options = []) {
          for (let i = 0; i < options.length; i++) {
            result.push(options[i].key)
            if (options[i].options && options[i].options.length > 0) {
              iteratorDic(options[i].options)
            }
          }
        }
        iteratorDic(finishMap)
        return result
      },
      // 获取options对象
      getSubFinishMap (superKey) {
        let result = []
        let options = this.getChannelDicByType('webchat') || []
        for (let i = 0; i < options.length; i++) {
          if (superKey === options[i].key) {
            result = options[i].options
            break
          }
          let options2 = options[i].options || []
          for (let j = 0; j < options2.length; j++) {
            if (superKey === options2[j].key) {
              result = options2[j].options
              break
            }
            let options3 = options2[j].options || []
            for (let k = 0; k < options3.length; k++) {
              if (superKey === options3[k].key) {
                result = options3[k].options
                break
              }
            }
          }
        }
        return result
      },
      // 导出在线咨询聊天记录弹窗
      exportChatRecordDialog () {
        this.exportDialogIsShow = true
        this.isExportTask = false
        this.exportDialogType = 'webchatExportChatRecord'
      },
      // 导出在线咨询聊天记录
      exportChatRecord (headData) {
        let that = this
        that.queryWebchatListCount(that.$store, that.activeName, that.qu).then((resp) => {
          if (resp.success) {
            let _count = resp.count
            if (_count > 20000) {
              that.$message.error(that.$t('webchat.exportMore20000Msg'))
              return
            }
            if (_count < 1) {
              that.$message.error(that.$t('webchat.exportChatRecordLess0'))
              return
            }
            let queryBadge = that.search[that.activeName].isChildren.adv.badgeList
            let query = {}
            if (queryBadge) {
              query = deepClone(that.search[that.activeName].isChildren.lastQuery)
            }
            if (!query) {
              query = {account: that.$store.state.session.account.account}
            } else {
              Object.assign(query, {account: that.$store.state.session.account.account})
            }
            if (that.$store.state.session.user && !that.$store.state.session.user.isAdmin) {
              Object.assign(query, {agentId: that.$store.state.session.user._id})
            }
            let flag = that.search[that.activeName].isChildren.nomalForm.flow
            if (flag && flag !== 'all') {
              let searchData = this.searchDataReturn(flag)
              Object.assign(query, {
                createTimeBegin: searchData.createTimeBegin,
                createTimeEnd: searchData.createTimeEnd
              })
            }
            delete query.limit
            delete query.page
            let data = {
              Method: 'exportWebchat',
              Query: query
            }
            Object.assign(query, {
              imHeads: headData.checkedExportHeads,
              custHeads: headData.checkedExportCustomerHeads
            })
            this.exportDialogIsShow = false
            this.$store.dispatch('exportWebchat', data)
          }
        })
      },
      // 导出在线咨询聊天内容弹窗
      exportChatContentDialog () {
        this.exportDialogIsShow = true
        this.isExportTask = true
        this.exportDialogType = 'webchatExportChatContent'
      },
      // 导出在线咨询聊天内容
      exportChatContent (headData) {
        let that = this
        that.queryWebchatListCount(that.$store, that.activeName, that.qu).then((resp) => {
          if (resp.success) {
            let _count = resp.count
            if (_count > this.exportTaskLimit.webchatContent) {
              this.$message.error(this.$t('business.exportBusinessLimit', {length: that.exportTaskLimit.webchatContent}))
              return
            }
            if (_count < 1) {
              that.$message.error(that.$t('webchat.exportChatContentLess0'))
              return
            }

            let queryBadge = that.search[that.activeName].isChildren.adv.badgeList
            let query = {}
            if (queryBadge) {
              query = deepClone(that.search[that.activeName].isChildren.lastQuery)
            }
            if (!query) {
              query = {account: that.$store.state.session.account.account}
            } else {
              Object.assign(query, {account: that.$store.state.session.account.account})
            }
            if (that.$store.state.session.user && !that.$store.state.session.user.isAdmin) {
              Object.assign(query, {agentId: that.$store.state.session.user._id})
            }
            let flag = that.search[that.activeName].isChildren.nomalForm.flow
            delete query.limit
            delete query.page
            let data = {
              Method: 'exportWebchat',
              Query: query
            }
            if (flag && flag !== 'all') {
              let searchData = this.searchDataReturn(flag)
              this.$set(data.Query, 'createTimeBegin', searchData.createTimeBegin)
              this.$set(data.Query, 'createTimeEnd', searchData.createTimeEnd)
            }
            Object.assign(query, {
              imHeads: headData.checkedExportHeads,
              custHeads: headData.checkedExportCustomerHeads,
              comment: headData.textarea
            })
            this.exportDialogIsShow = false
            this.$store.dispatch('exportWebchatContent', data)
          }
        })
      },
      exportDialogCancelFun () {
        this.exportDialogIsShow = false
      },
      // 导出弹窗确定事件
      exportDialogDefineFun (data) {
        if (data.exportType === 'webchatExportChatContent') {
          this.exportChatContent(data)
        } else {
          this.exportChatRecord(data)
        }
      },
      getChannelDicByType (type) {
        // let channelDic = this.$store.state.session.dicMap.channelDic
        let channelDic = this.$getCache('channelDic')
        let result = []
        for (let i = 0; i < channelDic.length; i++) {
          if (channelDic[i].type === type) {
            result = channelDic[i].options
            break
          }
        }
        return result
      },
      closePopConversation () {
        this.popConversationInfo.open = false
      },
      inviteInfo () {
        let that = this
        that.popConversationInfo.open = true
        that.popConversationInfo.loading = true
        this.$store.dispatch('getSessionsByAccount', {pageSize: 10, page: 1}).then((res) => {
          if (res && res.success) {
            that.popConversationInfo.loading = false
          }
        })
      },
      notifyRouteJump (data) {
        this.childTabActiveName = data.leaveMsg ? 'leaveSession' : 'onlineSession'
      },
      initiatingWebchatFun (res, type) {
        if (type === 'grabWebchatSession') {
          this.changeTab('webchat_todo', 'grabWebchatSession')
        }
        this.childTabActiveName = res ? 'leaveSession' : 'onlineSession'
      },
      // 点击质检提醒跳转在线
      routeToMe (to, from) {
        let query = this.$route.query
        if (query && query.active && query.webchatId) {
          // this.activeName = query.active
          let form = {'_id': query.webchatId, 'page': 1, 'limit': 10, 'morePage': 1, 'submenu': 'webchat_all'}
          this.$store.dispatch('queryWebchatList', form).then((res) => {
            this.loading = false
            this.pages = 1
            if (res && res.list.length) {
              this.$router.push('/index/webchat/' + query.active + '/' + query.webchatId)
              // this.$store.commit('call/REFRESH_CUST_RIGHT', Math.random())
            } else {
              this.$router.push('/index/webchat/' + query.active)
            }
            if (from && from.path.indexOf('webchat_') > -1) {  // 当前在在线模块，跳转进来
              this.activeName = query.active
              this.addLoad(this.activeName)
            }
          })
        }
      },
      handleConfirmNewItemsConfig ({data: formItemsConfig, done}, activeName) {
        var formItemsConfigs = deepClone(this.formItemsConfigs)
        formItemsConfigs[activeName] = formItemsConfig

        this.$store.dispatch('saveAdvSearchConfig', {
          searchType: 'WebchatCardGroup',
          config: formItemsConfigs
        }).then(() => {
          this.formItemsConfigs = formItemsConfigs
          done()
        })
      },
      changeActiveName () {
        const routeArr = this.$route.path.split('/')
        this.activeName = routeArr[3]  // 在其他模块操作时，点击在线浏览器提醒
        this.addLoad(this.activeName)
      }
    },
    activated () { // keep-alive 组件激活时
      this.changeActiveName()
    },
    computed: {
      webchatLimit () {
        let data = {
          value: '',
          options: []
        }
        let currentUser = this.$store.state[this.type].currentUser
//        超级管理员登录currentUser为null
        if (currentUser) {
          let max = parseInt(currentUser.maxImDealCount)
          let min = parseInt(currentUser.minImDealCount)
          if (currentUser.imDealCount < min) {
            currentUser.imDealCount = min
          } else if (currentUser.imDealCount > max) {
            currentUser.imDealCount = max
          }
          data.value = currentUser.imDealCount
          for (let i = min; i <= max; i++) {
            data.options.push({label: i, value: i})
          }
        }
        return data
      },
      refreshWebchatSummary () {
        return this.$store.state.webchat.refreshWebchatSummary
      },
      cardList () {
        if (this.$store.state.webchat.webchatList[this.activeName] && this.activeName) {
          let cardList = this.$store.state.webchat.webchatList[this.activeName].list || []
          return cardList
          console.log(cardList)
        } else {
          return []
        }
      },
      count () {
        if (this.$store.state.webchat.webchatList[this.activeName] && this.activeName) {
          return this.$store.state.webchat.webchatList[this.activeName].count || 0
        } else {
          return 0
        }
      },
      moreFlag () {
        if (this.$store.state.webchat.webchatList[this.activeName] && this.activeName) {
          if (this.$store.state.webchat.webchatList[this.activeName].more) {
            return true
          } else {
            return false
          }
        } else {
          return false
        }
      },
      totalPage () {
        if (this.$store.state.webchat.webchatList[this.activeName] && this.$store.state.webchat.webchatList[this.activeName].count) {
          let num = parseInt(deepClone(this.$store.state.webchat.webchatList[this.activeName].count))
          return Math.ceil(num / 10) || 0
        }
      },
      tabPanes () {
        // 传入的tab数组
        let todoNum = parseInt(deepClone(this.$store.state.webchat.todoNum))
        let listCount = this.$store.state.webchat.webchatList.webchat_todo.count || 0
        if (listCount > todoNum) {
          todoNum = listCount
        }
        if (todoNum > 99) {
          todoNum = '99+'
        }
        let webchatLimit = this.webchatLimit.value || 0
        let tabName = [
          {name: this.$t('webchat.webchatTodo') + todoNum + '/' + webchatLimit, type: 'webchat_todo'},
          {name: this.$t('webchat.webchatRobot'), type: 'webchat_robot'},
          {name: this.$t('webchat.webchatAll'), type: 'webchat_all'}
          // {name: this.$t('webchat.webchatLaterProcess'), type: 'webchat_laterProcess'}
        ]
        // 是否有机器人tab权限
        if (this.$store.state.session.user.funcIds && !contains(this.$store.state.session.user.funcIds, 'func_robot_session')) {
          tabName.splice(1, 1)
        }
        return tabName
      }
    },
    components: {
      WebchatCard,
      Search,
      'v-select': Select,
      PopDragConversation,
      DropdownMenu,
      CardGroupSolt,
      InputSearch,
      AdvancedSearch,
      AdvSchBadge,
      Pagination,
      TimeSearch,
      Refresh,
      Export,
      ExportDialog
    },
    mounted () {
      this.changeActiveName() // 因为cardGroup上的v-if,导致首次加载组件时，没法触发activated钩子
      this.exportTaskLimit = this.$getCache('exportTaskLimit') || {}
      // 监听稍后处理tab的刷新时间刷新稍后处理列表
      bus.$on('laterProcessRefresh', (msg) => {
        this.handleRefresh(msg)
      })
      bus.$on('webchatJumpRoute', (res) => {
        this.notifyRouteJump(res)
      })
      bus.$on('initiatingWebchatFun', (res, type) => {
        this.initiatingWebchatFun(res, type)
      })
    },
    beforeDestroy () {
      bus.$off('laterProcessRefresh')
      bus.$off('webchatJumpRoute')
      bus.$off('initiatingWebchatFun')
    }
  }
  function getFinishType (finishOption) {
    let finishKeys = []
    for (let i = 0; i < finishOption.length; i++) {
      finishKeys.push({label: finishOption[i].name, value: `${finishOption[i].key}__${finishOption[i].name}`})
      let level2 = deepClone(finishOption[i].options)
      if (level2) {
        for (let m = 0; m < level2.length; m++) {
          level2[m].name = finishOption[i].name + '->' + level2[m].name
          finishKeys.push({label: level2[m].name, value: `${level2[m].key}__${level2[m].name}`})
          let level3 = deepClone(level2[m].options)
          if (level3) {
            for (let n = 0; n < level3.length; n++) {
              level3[n].name = level2[m].name + '->' + level3[n].name
              finishKeys.push({label: level3[n].name, value: `${level3[n].key}__${level3[n].name}`})
            }
          }
        }
      }
    }
    return finishKeys
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .loading
    z-index 1999
    height 500px
  .card_list_select
    max-width 80px
  .chat_limit
    width 70px  
  .time_search
    margin-left auto
    max-width 180px
    margin-right 0px !important
  .font12
    margin 0 7px
    color $cf-gray1
  .childTab
    margin-left 6px
    width 180px
  .avatar
    margin 0 11px 0 3px
    width 52px
    height 52px
    line-height 52px
    flex-shrink 0
    text-align center
    font-size 32px
    border-radius 50%
    color white
    background-color $c-main
    &.offline
      filter grayscale(100%)
      background-color #e0e0e0
</style>
<style lang="stylus">
  .childTab
    .el-radio-button--small .el-radio-button__inner
      padding 8px 15px
      color #459AE9
      width 90px
      background-color #F0F2F3
      border 1px solid #459AE9
    .el-radio-button__orig-radio:checked+.el-radio-button__inner
      color #ffffff
      background-color #459AE9
</style>